import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt

# 读取数据
data = pd.read_csv('cleaned_Spambase.csv')

# 划分特征和标签
X = data.iloc[:, :-1]  # 获取除最后一列之外的所有列作为特征X
y = data.iloc[:, -1]   # 获取最后一列作为标签y

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 数据标准化
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# 构建朴素贝叶斯模型
nb_model = GaussianNB()

# 训练朴素贝叶斯模型
nb_model.fit(X_train, y_train)

# 使用朴素贝叶斯模型进行分类
y_pred_nb = nb_model.predict(X_test)

# 计算准确率
accuracy_nb = accuracy_score(y_test, y_pred_nb)
print("Accuracy (Naive Bayes): ", accuracy_nb)

# 构建Boosting分类器
boosting_model = AdaBoostClassifier(base_estimator=nb_model, n_estimators=50)

# 训练Boosting模型
boosting_model.fit(X_train, y_train)

# 使用Boosting模型进行分类
y_pred_boosting = boosting_model.predict(X_test)

# 计算准确率
accuracy_boosting = accuracy_score(y_test, y_pred_boosting)
print("Accuracy (Naive Bayes with Boosting): ", accuracy_boosting)


# 构建Bagging分类器
bagging_model = BaggingClassifier(base_estimator=nb_model, n_estimators=50)

# 训练Bagging模型
bagging_model.fit(X_train, y_train)

# 使用Bagging模型进行分类
y_pred_bagging = bagging_model.predict(X_test)

# 计算准确率
accuracy_bagging = accuracy_score(y_test, y_pred_bagging)
print("Accuracy (Naive Bayes with Bagging): ", accuracy_bagging)


# 创建一个条形图
model_names = ['Naive Bayes', 'Naive Bayes with Bagging', 'Naive Bayes with Boosting']
accuracy_scores = [accuracy_nb, accuracy_bagging, accuracy_boosting]

plt.bar(model_names, accuracy_scores)
#plt.ylim(0.9, 1)   # 设置y轴范围

# 添加标题和标签
plt.title('Accuracy Comparison')
plt.xlabel('Model')
plt.ylabel('Accuracy')

plt.show()


